# Copyright(c) 2008 Tri Tech Information Systems Inc. 
# Distributed under the Boost Software License, Version 1.0.
#     (See accompanying file LICENSE_1_0.txt or copy at
#           http://www.boost.org/LICENSE_1_0.txt)
#     
"""
This is a little script to write licenses to all files
"""

import os.path

class BaseSource(object):
    def __init__(self, path):
        self.path = path

    def extract_comment_header(self):
        input = open(self.path)

        header_lines = []
        for line in input:
            if not line.startswith(self.comment_start):
                break
#            if not line[2:].strip():
#                break
            header_lines.append(line[2:])

        return "\n".join(header_lines)

    def write_header(self, text, delete_header):
        lines = open(self.path).readlines()

        if delete_header:
            idx = 0
            for line in lines:
                if not line.startswith(self.comment_start):
                    break
                idx += 1
#                if not line[2:].strip():
#                    break
            del lines[:idx]

        lines = [self.comment_start + ' ' + line + '\n' for line in text.split('\n')] + lines

        open(self.path, "w").write(''.join(lines))

class CPPSource(BaseSource):
    comment_start = '//'

class PySource(BaseSource):
    comment_start = '#'

SOURCE_HANDLERS = {
    '.h' : CPPSource,
    '.cpp' : CPPSource,
    '.py' : PySource,
    '.pyx' : PySource,
}

LICENSE_TEXTS = [
    'copyright',
    'license',
    'rights reserved'
]


def is_license(text):
    text = text.lower()
    for words in LICENSE_TEXTS:
        if text.find(words) != -1:
            return True
    return False

    

def handle_file(path, template):
    basename, ext = os.path.splitext(path)
    
    try:
        handler = SOURCE_HANDLERS[ext]
    except KeyError:
        print "Skipping", path
        return
    else:
        handler = handler(path)

    
    comment_header = handler.extract_comment_header()

    has_license = is_license(comment_header)

    license_text = template(path)

    handler.write_header(license_text, has_license)


def handle_dir(path, template):
    for path, dirs, files in os.walk(path, True):
        dirs[:] = [d for d in dirs if d[0] != '.']
        for file in files:
            handle_file( os.path.join(path, file), template)

def relative_path(path, relative_to):
    path = os.path.abspath(path)
    relative_to = os.path.abspath(relative_to)

    path = path.split(os.sep)
    relative_to = relative_to.split(os.sep)

    # eliminate common parts
    while path[0] == relative_to[0]:
        path.pop(0)
        relative_to.pop(0)

    backtracking = len(relative_to) - 1

    relative_path = ['..'] * backtracking + path
    return os.path.join(*relative_path)
BOOST_LICENSE_PATH = os.path.abspath('LICENSE_1_0.txt')

def boost_license(path):
    rel_path = relative_path(BOOST_LICENSE_PATH, path)
    return """Copyright(c) 2008 Tri Tech Information Systems Inc. 
Distributed under the Boost Software License, Version 1.0.
    (See accompanying file %s or copy at
          http://www.boost.org/LICENSE_1_0.txt)
    """ % rel_path

def gpl_license(path):
    return """  Copyright (C) 2008      Tri Tech Information Systems Inc.

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License along
  with this program; if not, write to the Free Software Foundation, Inc.,
  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  """

handle_dir('include', boost_license)
handle_dir('src', boost_license)
handle_dir('tests', boost_license)
handle_dir('examples', boost_license)

handle_dir('pyxx', gpl_license)

# basically, I couldn't pass up the opprotunity to run a script on itself
handle_file(__file__, boost_license)
